/**
 * 
 */
package com.srini.exception;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Sriniz
 * 
 */
public class ErrorHandler extends HttpServlet {

	private static final long serialVersionUID = -8423184718886468273L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("Handling the error...");

		// Analyze the servlet exception
		String message = "";
		Throwable throwable = (Throwable) req
				.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) req
				.getAttribute("javax.servlet.error.status_code");

		// Set response content type
		resp.setContentType("text/html");

		System.out.println(throwable + " - " + statusCode);

		switch (statusCode) {
		case 404:
			message = "The page you requested is not available.";
			break;
		case 405:
			message = "The page you requested is not available.";
			break;
		case 500:
			message = "Internal server error is occurred. Inconvenience caused regreted.";
			break;
		default:
			message = "An unexpected error was occurred. Inconvenience caused regreted.";
			break;
		}
		req.setAttribute("errorMessage", message);
		RequestDispatcher dispatcher = req
				.getRequestDispatcher("/errorPage.jsp");
		dispatcher.forward(req, resp);

	}
}
